import type React from "react";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { Card, Select, List, Button, Form, Spin, Typography } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import sopService from "@/api/services/mes/sopService";
import workshopService from "@/api/services/mes/workshopService";
import type { SopDocument, SopSendRecord, SopTerminal } from "./entity";
import type { MesWorkshop } from "../workshop/entity";
import { toast } from "sonner";
import terminalService from "@/api/services/mes/terminalService";

const { Title } = Typography;

interface Props {
	managerId: React.Key;
}

export interface SendDocPageRef {
	saveSendDoc: () => Promise<void>;
}

const SendDocPage = forwardRef<SendDocPageRef, Props>(({ managerId }, ref) => {
	const [loading, setLoading] = useState(false);
	const [documentList, setDocumentList] = useState<SopDocument[]>([]);
	const [workshopOptions, setWorkshopOptions] = useState<MesWorkshop[]>([]);
	const [lineOptions, setLineOptions] = useState<MesWorkshop[]>([]);
	const [terminalList, setTerminalList] = useState<SopTerminal[]>([]);
	const [searchForm] = Form.useForm();
	const [dragOverId, setDragOverId] = useState<string | null>(null);

	useEffect(() => {
		getDocumentList(managerId);
		getWorkshopOptions();
	}, [managerId]);

	const getDocumentList = async (managerId: string) => {
		await sopService.getdocuments(managerId).then((res) => {
			setDocumentList(res);
		});
	};

	const getWorkshopOptions = () => {
		workshopService
			.getWorkshopSelectList()
			.then((res) => {
				setWorkshopOptions(res);
			})
			.catch((error) => {
				console.error("获取车间列表失败：", error);
				toast.error("获取车间列表失败");
			});
	};

	const getLineOptions = async (workshopId: number) => {
		await workshopService
			.getLineSelectList(workshopId)
			.then((res) => {
				setLineOptions(res);
			})
			.catch((error) => {
				console.error("获取产线列表失败：", error);
				toast.error("获取产线列表失败");
			});
	};

	const searchTerminal = async (values: any) => {
		setLoading(true);
		await terminalService
			.list(values)
			.then((res) => {
				setTerminalList(res);
			})
			.catch((error) => {
				console.error("查询终端失败：", error);
				toast.error("查询终端失败");
			})
			.finally(() => {
				setLoading(false);
			});
	};

	const handleDragStart = (document: SopDocument) => (e: React.DragEvent) => {
		e.dataTransfer.setData("documentId", document.id);
	};

	const handleDragEnter = (terminalId: string) => () => {
		setDragOverId(terminalId);
	};
	const handleDragLeave = () => {
		setDragOverId(null);
	};

	const handleDragOver = (terminalId: string) => (e: React.DragEvent) => {
		e.preventDefault();
		setDragOverId(terminalId);
	};

	const handleDrop = (terminalId: string) => (e: React.DragEvent) => {
		e.preventDefault();
		setDragOverId(null);
		const documentId = e.dataTransfer.getData("documentId");
		const document = documentList.find((f) => f.id === documentId);
		if (!document) return;

		// 检查是否已存在
		const targetTerminal = terminalList.find((t) => t.id === terminalId);
		if (targetTerminal?.documentList?.some((f) => f.id === documentId)) {
			toast.warning("该文件已存在于此设备卡片中");
			return;
		}

		setTerminalList((prev) =>
			prev.map((terminal) =>
				terminal.id === terminalId
					? { ...terminal, documentList: [...(terminal.documentList ?? []), document] }
					: terminal,
			),
		);
		toast.success(`文件已分配到设备`);
	};

	const handleRemoveFile = (terminalId: string, documentId: string) => {
		setTerminalList((prev) =>
			prev.map((dev) =>
				dev.id === terminalId ? { ...dev, documentList: dev.documentList?.filter((f) => f.id !== documentId) } : dev,
			),
		);
	};

	useImperativeHandle(ref, () => ({
		saveSendDoc: async () => {
			const sendRecordList: SopSendRecord[] = [];
			terminalList.forEach((terminal) => {
				terminal.documentList?.forEach((document) => {
					sendRecordList.push({
						manageId: managerId,
						terminalId: terminal.id,
						ip: terminal.ip,
						documentId: document.id,
						fileName: document.fileName,
						fileType: document.fileType,
						fileSize: document.fileSize,
						lineId: terminal.lineId,
						stationId: terminal.stationId,
						status: "1",
					});
				});
			});
			await sopService.sendDoc(sendRecordList);
		},
	}));

	return (
		<div
			style={{
				display: "flex",
				gap: 32,
				alignItems: "flex-start",
				minHeight: "calc(100vh - 220px)",
			}}
		>
			{/* 左侧文件列表 */}
			<Card
				title={
					<Title level={5} style={{ margin: 0 }}>
						文件列表
					</Title>
				}
				style={{
					width: 300,
					minHeight: 480,
					boxShadow: "0 2px 12px rgba(0,0,0,0.08)",
					borderRadius: 12,
					background: "#fff",
					padding: 16,
				}}
				bodyStyle={{ padding: 16, maxHeight: 600, overflowY: "auto" }}
			>
				<List
					dataSource={documentList}
					locale={{ emptyText: "暂无文件" }}
					renderItem={(document) => (
						<List.Item
							key={document.id}
							draggable
							onDragStart={handleDragStart(document)}
							style={{
								cursor: "grab",
								padding: "8px 10px",
								borderBottom: "1px solid #f0f0f0",
								background: "#fafbfc",
								borderRadius: 6,
								marginBottom: 4,
							}}
						>
							<span style={{ fontWeight: 500 }}>{document.fileName}</span>
						</List.Item>
					)}
				/>
			</Card>

			{/* 右侧设备卡片 */}
			<div style={{ flex: 1 }}>
				<Card
					style={{
						marginBottom: 24,
						boxShadow: "0 2px 12px rgba(0,0,0,0.08)",
						borderRadius: 12,
						background: "#fff",
					}}
					bodyStyle={{ padding: 24 }}
				>
					<Form form={searchForm} layout="inline" onFinish={searchTerminal} style={{ marginBottom: 0 }}>
						<Form.Item label="车间" name="workshopName">
							<Select
								placeholder="请选择车间"
								style={{ width: 160 }}
								options={workshopOptions.map((item) => ({
									label: item.name,
									value: item.id,
								}))}
								onChange={(value) => getLineOptions(value)}
								allowClear
							/>
						</Form.Item>
						<Form.Item label="产线" name="lineName">
							<Select
								placeholder="请选择产线"
								style={{ width: 160 }}
								options={lineOptions.map((item) => ({
									label: item.name,
									value: item.id,
								}))}
								allowClear
							/>
						</Form.Item>
						<Form.Item>
							<Button type="primary" htmlType="submit">
								查询
							</Button>
						</Form.Item>
						<Form.Item>
							<Button
								style={{ marginLeft: 8 }}
								onClick={() => {
									searchForm.resetFields();
								}}
							>
								重置
							</Button>
						</Form.Item>
					</Form>
				</Card>
				<div style={{ marginBottom: 12 }}>
					<Title level={5} style={{ margin: 0 }}>
						终端信息
					</Title>
				</div>
				<Spin spinning={loading} tip="数据加载中..." size="large">
					<div
						style={{
							display: "flex",
							gap: 20,
							flexWrap: "wrap",
							alignItems: "flex-start",
							minHeight: 300,
							maxHeight: 520,
							overflowY: "auto",
							padding: "10px 10px",
						}}
					>
						{terminalList.length === 0 ? (
							<div style={{ color: "#aaa", padding: 32 }}>请先查询设备</div>
						) : (
							terminalList.map((terminal) => (
								<Card
									key={terminal.id}
									title={
										<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
											<span style={{ fontWeight: 500 }}>{terminal.name}</span>
											{terminal.stationName && (
												<span style={{ color: "#888", fontSize: 13 }}>工位：{terminal.stationName}</span>
											)}
										</div>
									}
									style={{
										width: 240,
										minHeight: 180,
										boxShadow:
											dragOverId === terminal.id
												? "0 0 0 3px #1677ff, 0 2px 8px rgba(0,0,0,0.06)"
												: "0 2px 8px rgba(0,0,0,0.06)",
										borderRadius: 10,
										background: "#f9fafb",
										transition: "box-shadow 0.2s",
									}}
									bodyStyle={{ padding: 16 }}
									onDrop={handleDrop(terminal.id)}
									onDragOver={handleDragOver(terminal.id)}
									onDragEnter={handleDragEnter(terminal.id)}
									onDragLeave={handleDragLeave}
								>
									<div>
										{terminal.documentList?.length === 0 ? (
											<span style={{ color: "#bbb" }}>拖入文件到此设备</span>
										) : (
											<List
												dataSource={terminal.documentList}
												locale={{ emptyText: "暂无文件" }}
												renderItem={(document) => (
													<List.Item
														key={document.id}
														style={{
															background: "#fff",
															borderRadius: 6,
															marginBottom: 6,
															padding: "6px 8px",
															boxShadow: "0 1px 4px rgba(0,0,0,0.04)",
															display: "flex",
															alignItems: "center",
														}}
														actions={[
															<Button
																type="text"
																icon={<DeleteOutlined />}
																size="small"
																danger
																onClick={() => handleRemoveFile(terminal.id, document.id)}
															/>,
														]}
													>
														<span style={{ fontWeight: 500 }}>{document.fileName}</span>
													</List.Item>
												)}
											/>
										)}
									</div>
								</Card>
							))
						)}
					</div>
				</Spin>
			</div>
		</div>
	);
});

export default SendDocPage;
